package com.levi.completableFuture;

import java.util.concurrent.*;
import java.util.function.BiConsumer;
import java.util.function.Function;

/**
 * @author shentong
 * @since 2022/1/16 4:21 PM
 */
public class WhencompleteDemo {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            int i = 1/0;
            System.out.println(Thread.currentThread().getName());
            return 123;
        }, executorService);
        System.out.println("Main End~");
        try {
            Integer integer = future.get();
            System.out.println(integer);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        //对异步任务的结果进行进一步的处理
        future.whenCompleteAsync(new BiConsumer<Integer, Throwable>() {
            //integer是异步任务的返回值
            @Override
            public void accept(Integer integer, Throwable throwable) {
                System.out.println("进一步处理任务的线程是:"+Thread.currentThread().getName());
                System.out.println(integer+1);
                executorService.shutdown();
            }
        },executorService);
        future.exceptionally(new Function<Throwable, Integer>() {
            @Override
            public Integer apply(Throwable throwable) {
                System.out.println("出现异常了，"+Thread.currentThread().getName());
                return null;
            }
        });

    }
}
